package com.qiu.greened.ui.main

import android.app.Application
import androidx.lifecycle.*
import androidx.paging.*
import com.qiu.greened.bean.PostBean
import com.qiu.greened.data.PostHotPagingSource
import com.qiu.greened.network.PostService
import com.qiu.greened.network.ServiceCreator
import kotlinx.coroutines.flow.Flow

class HomeViewModel(application: Application) : AndroidViewModel(application) {

    private val postService by lazy {
        ServiceCreator.create<PostService>()
    }

//    val listData = Pager(PagingConfig(pageSize = 10)) {
//        PostPagingSource(postService)
//    }.flow.cachedIn(viewModelScope)

    /**
     * cachedIn() 将服务器返回的数据在 viewModelScope 这个作用域内进行缓存
     */
    fun getPagingData(): Flow<PagingData<PostBean>> {
        return Pager(PagingConfig(pageSize = 10)) {
            PostHotPagingSource(postService)
        }.flow.cachedIn(viewModelScope)
    }


//    var pagedlistLiveData = LivePagedListBuilder<Int, PlayItem>(
//        PlaylistDataSourceFactory(type, viewModelScope),
//        PagedList.Config.Builder().setPageSize(15).build()
//    ).build()
//
//    fun resetQuery() {
//        pagedlistLiveData.value?.dataSource?.invalidate()
//    }

//    private val _postHotList = MutableLiveData<List<PostBean>>().apply {
//        loadPostHotList()
//    }
//
//    var postHotList: LiveData<List<PostBean>> = _postHotList
//    private fun loadPostHotList() {
//        viewModelScope.launch {
//            try {
//                val data = ServiceCreator.create<PostService>()
//                    .getPostHot(1, 10).dataConvert()
//                /*给LiveData赋值  ui会自动更新*/
//                _postHotList.value = data
//
//            } catch (e: Exception) {
//                e.printStackTrace()
//                Log.i("请求失败", "${e.message}")
//            }
//        }
//    }
}
